package cn.xfdzx.android.apps.shop.activity;

import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.GoodsLimitListAdapter;
import cn.xfdzx.android.apps.shop.adapter.GoodsLimitListHeadAdapter;
import cn.xfdzx.android.apps.shop.adapter.GoodsLimitListHead_TagAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.GoodsLimitBean;
import cn.xfdzx.android.apps.shop.bean.GoodsMiaoSBean;
import cn.xfdzx.android.apps.shop.contract.GoodsLimitContract;
import cn.xfdzx.android.apps.shop.presenter.GoodsLimitPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.widget.recyclemanager.ScaleLayoutManager;

/*
/* 页面批发商品限量活动
 */
public class XFDGoodsLimitActivity extends BaseMvpActivity<GoodsLimitPresenter> implements GoodsLimitContract.View, View.OnClickListener {
    private ImageView ivBack;      //标题栏-左边按钮
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView recyclerView;
    private String limit = "10";
    private int page  = 1;
    private RelativeLayout.LayoutParams item_bar;
    private LinearLayout llState;
    private GoodsLimitListAdapter goodsLimitListAdapter;//商品列表
    private List<GoodsLimitBean.DataBean> dataBeans;
    private RecyclerView recycle_goodslimit_head;//头部横向列表
    private GoodsLimitListHeadAdapter headAdapter;//商品头部列表
    private RecyclerView recycle_tag_head;//头部横向列表下方指示器标签
    private GoodsLimitListHead_TagAdapter tagAdapter;//头部横向列表下方指示器标签
    private List<GoodsLimitBean.DataBean> data;
    private ImageView img_returntop;//返回顶部
    private int mLastVisiblePosition;//列表最后一个可见视图角标
    private String good_Id;

    @Override
    public int getLayoutId() {
        return R.layout.activity_goodslimit;
    }

    @Override
    public void initView() {
        mPresenter = new GoodsLimitPresenter();
        mPresenter.attachView(this);
        mRefreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recycle_goodslimit);
        ivBack = findViewById(R.id.iv_back);
        llState = findViewById(R.id.ll_state);
        img_returntop = findViewById(R.id.img_returntop);
        ivBack.setOnClickListener(this);
        img_returntop.setOnClickListener(this);
        initHigh();
        initRecycle();
        mPresenter.getGoodsLimitList(true,true,limit,page);
        mPresenter.getGoodsLimitListHighSales();

    }


    private void initHigh() {

        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    private void initRecycle() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        goodsLimitListAdapter = new GoodsLimitListAdapter(dataBeans);
        recyclerView.setAdapter(goodsLimitListAdapter);
        View headView  = LayoutInflater.from(this).inflate(R.layout.activity_goodslimit_head, recyclerView, false);
        recycle_goodslimit_head = headView.findViewById(R.id.recycle_goodslimit_head);
        recycle_tag_head = headView.findViewById(R.id.recycle_tag_head);
        goodsLimitListAdapter.addHeaderView(headView);

        //列表去购买点击判断库存
        goodsLimitListAdapter.setOnListItemGoBuyListener(new GoodsLimitListAdapter.OnItemOnClickListener() {
            @Override
            public void onItemBuyClick(String goodsId) {
                good_Id = goodsId;
                mPresenter.getLimitGoodsStock(good_Id);
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
        recycle_tag_head.setLayoutManager(layoutManager);
        tagAdapter = new GoodsLimitListHead_TagAdapter(dataBeans);
        recycle_tag_head.setAdapter(tagAdapter);

        ScaleLayoutManager scaleLayoutManager =  new ScaleLayoutManager(this, Utils.dp2px(this, -20));

        recycle_goodslimit_head.setLayoutManager(scaleLayoutManager);
        new LinearSnapHelper().attachToRecyclerView(recycle_goodslimit_head);
        headAdapter = new GoodsLimitListHeadAdapter(dataBeans);
        recycle_goodslimit_head.setAdapter(headAdapter);
        recycle_goodslimit_head.setOnScrollListener(new RecyclerView.OnScrollListener() {
            //用来标记是否正在向最后一个滑动
            boolean isSlidingToLast = false;

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition
//                    LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
//                    int totalItemCount = scaleLayoutManager.getItemCount();

                    scaleLayoutManager.getCurrentPosition();
                    for (int i = 0; i < data.size(); i++) {
                        data.get(i).setSel(false);
                    }
                    data.get(scaleLayoutManager.getCurrentPosition()).setSel(true);
                    tagAdapter.refreshDatas(data);
//                    // 判断是否滚动到底部，并且是向右滚动
//                    if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
//                        //加载更多功能的代码
//                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if (dx > 0) {
                    //大于0表示正在向右滚动
                    isSlidingToLast = true;
                } else {
                    //小于等于0表示停止或向左滚动
                    isSlidingToLast = false;
                }
            }
        });

        //横向列表去购买点击
        headAdapter.setOnItemGoBuyListener(new GoodsLimitListHeadAdapter.OnItemOnClickListener() {
            @Override
            public void onItemBuyClick(String goodsId) {
                good_Id = goodsId;
                mPresenter.getLimitGoodsStock(good_Id);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE || newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    // DES: 找出当前可视Item位置
                    RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                    if (layoutManager instanceof LinearLayoutManager) {
                        LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                        //mFirstVisiblePosition = linearManager.findFirstVisibleItemPosition();
                        mLastVisiblePosition = linearManager.findLastVisibleItemPosition();
                        if (mLastVisiblePosition>6){
                            img_returntop.setVisibility(View.VISIBLE);
                        }else {
                            img_returntop.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.e("","");
            }
        });

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                page = 1;
                mPresenter.getGoodsLimitList(true,true,limit,page);

            }
        });


     }

    @Override
    protected void onResume() {
        super.onResume();
//        page = 1;
//        mPresenter.getFollowList(true,true,limit,page);
    }

    @Override
    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(true);//加载完成
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void getGoodsLimitListSuccess(GoodsLimitBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (page == 1) {
                mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        mPresenter.getGoodsLimitList(false, true, limit, page);
                    }
                });

                if (EmptyUtil.isNotEmpty(bean.getData())) {
                    goodsLimitListAdapter.refreshDatas(bean.getData());
                }else {
                    mRefreshLayout.finishLoadMoreWithNoMoreData();
                }
            } else {

                if (EmptyUtil.isEmpty(bean.getData())) {
                    mRefreshLayout.finishLoadMoreWithNoMoreData();
                } else {
                    goodsLimitListAdapter.addDatas(bean.getData());
                    page++;
                }


            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getGoodsLimitListHighSalesSuccess(GoodsLimitBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (EmptyUtil.isNotEmpty(bean.getData())) {
                headAdapter.refreshDatas(bean.getData());

                data = bean.getData();
                data.get(0).setSel(true);
                tagAdapter.refreshDatas(data);
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getGoodsMiaoShaListSuccess(GoodsMiaoSBean bean) {

    }

    @Override
    public void getGoodsStockSuccess(GoodsMiaoSBean bean) {

    }

    @Override
    public void getLimitGoodsStockSuccess(GoodsMiaoSBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (bean.getData().getStock()>0){
                Intent intent = new Intent(this, XFDGoodsDeatailsActivity.class);
                intent.putExtra("good_id",good_Id);
                startActivity(intent);
            }else {
                Toast.makeText(this, "很抱歉，该商品已被抢光", Toast.LENGTH_SHORT).show();
                page=1;
                mPresenter.getGoodsLimitList(true,true,limit,page);
                mPresenter.getGoodsLimitListHighSales();
            }

        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        if (EmptyUtil.isNotEmpty(mPresenter))
        mPresenter.detachView();
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:    //返回按钮点击
                finish();
                break;
            case R.id.img_returntop://返回顶部
                recyclerView.scrollToPosition(0);
                img_returntop.setVisibility(View.GONE);
                break;
        }
    }
}
